<template>
  <el-card :body-style="{padding: 0, height: '100%'}" style="height: 100%" shadow="always">
    <div id="header">
      <span>好友列表</span>
      <el-popover v-model="isMsgShown" style="overflow: auto" width="400">
        <el-card v-for="message in messageList" :key="message.id"
                 :body-style="cardStyle" shadow="hover">
          <img :src="message.user+'.png'" alt="" loading="lazy" style="border-radius: 50%" width="50">
          <pre>{{showMessage(message)}}</pre>
          <el-button-group v-if="message.action === 'add'">
            <el-button type="primary" @click="agreeAdd(message.user)">同意</el-button>
            <el-button type="danger" @click="refuseAdd(message.user)">拒绝</el-button>
          </el-button-group>
          <el-button-group v-if="message.action === 'del'">
            <el-button type="primary" @click="tryAgain(message)">挽回</el-button>
            <el-button @click="giveUp(message)">算了</el-button>
          </el-button-group>
          <el-button-group v-if="message.action === 'ref'">
            <el-button type="primary" @click="tryAgain(message)">重试</el-button>
            <el-button @click="giveUp(message)">算了</el-button>
          </el-button-group>
          <el-button v-if="message.action === 'agr'" @click="giveUp(message)">好耶</el-button>
        </el-card>
        <el-badge slot="reference" :max="99" :value="messageList.length">
          <i class="el-icon-message"></i>
        </el-badge>
      </el-popover>
      <el-popover v-model="isAddShown" placement="bottom" trigger="click" width="250">
        <div id="addInput">
          <el-input v-model="addFriendName" placeholder="请输入用户名" type="text"/>
          <el-input v-model="remarks" maxlength="10" placeholder="备注内容"
                    show-word-limit type="text"/>
          <i class="el-icon-circle-plus" @click="addFriend"></i>
        </div>
        <i slot="reference" class="iconfont icon-add-friends"/>
      </el-popover>
    </div>

    <my-scroll>
      <el-card v-for="(friend, i) in friendList" :key="friend.id"
               :body-style="cardStyle" shadow="hover">
        <img :src="friend+'.png'" alt="" loading="lazy" style="border-radius: 50%" width="50">
        <span>{{friend}}</span>
        <el-button circle class="hide-button" icon="el-icon-delete" size="small"
                   type="danger" @click="deleteFriend(i)"></el-button>
      </el-card>
    </my-scroll>

  </el-card>
</template>

<script>
import {mapState} from "vuex";
import MyScroll from "@/components/MyScroll";
export default {
  name: "FriendList",
  components: { MyScroll },
  data() {
    return {
      addFriendName: '',
      remarks: '',
      isAddShown: false,
      isMsgShown: false,
      cardStyle: {
        display: 'grid',
        gap: '5%',
        gridTemplateColumns: '50px 6fr 1fr',
        alignItems: 'center',
        padding: '5px',
      },
    }
  },
  computed: {
    ...mapState(['friendList', 'serverUrl', 'token', 'messages']),
    headers() {
      return {Authorization: this.token}
    },
    messageList() {
      const list = [];
      for (const user in this.messages) {
        for (const action in this.messages[user]) {
          list.push({ user, action, remark: this.messages[user][action] })
        }
      }
      return list
    },
  },
  methods: {
    deleteFriend(i) {
      this.$confirm('确认删除好友吗？', '警告', {type: "warning"}).then(()=>{
        const username = this.friendList[i];
        const newFriendList = this.friendList.slice().splice(i, 1).join(';');
        this.$axios.put(this.serverUrl+'/user/delFriend', {newFriendList}, {
          headers: this.headers
        }).then(res => {
          if (res.data.status !== 0) {
            this.$alert(res.data.msg, '删除失败');
          } else {
            this.$store.state.friendList.splice(i, 1);
            this.$message.success(username + '已被移除你的好友列表');
          }
        }).catch(err => {
          this.$alert(err.message, '网络连接出错')
        })
      }).catch(() => this.$message.warning('删除已取消，要珍惜你的好友哦！'))
    },
    addFriend() {
      const reg = /^[\w\u4e00-\u9fa5]{6,12}$/;
      if (!reg.test(this.addFriendName)) {
        return this.$alert('用户名不存在', '添加失败');
      }
      if (this.friendList.includes(this.addFriendName)) {
        return this.$alert('该用户已经是您的好友了', '添加失败');
      }
      this.$axios.put(this.serverUrl+'/user/addFriend', {
        friendName: this.addFriendName,
        remarks: this.remarks,
      }, {
        headers: this.headers,
      }).then(res => {
        if (res.data.status !== 0) {
          this.$alert(res.data.msg, '请求发送失败');
        } else {
          this.$message.success('请求发送成功！');
          this.isAddShown = false;
        }
      }).catch(err => {
        this.$alert(err.message, '网络连接出错')
      })
    },
    showMessage(message) {
      const {user, action, remark} = message;
      let actionText;
      if (action === 'add') actionText = '申请加您为好友';
      else if (action === 'del') actionText = '删除了您的好友';
      else if (action === 'ref') actionText = '拒绝了您的好友申请';
      else if (action === 'agr') actionText = '同意了您的好友申请';
      return remark === '' ? `${user}\n${actionText}` :
          `${user}  ${actionText}\n备注：${remark}`
    },
    agreeAdd(username) {
      this.$axios.put(this.serverUrl+'/user/agree', {
        friend: username,
        friends: this.friendList.join(';'),
        messages: JSON.stringify(this.messages),
      }, {
        headers: this.headers
      }).then(res => {
        if (res.data.status !== 0) {
          this.$alert(res.data.msg, '添加失败');
        } else {
          this.$delete(this.$store.state.messages[username], 'add');
          this.$store.state.friendList.push(username);
          this.$message.success('添加成功！'+username+'已经是你的好友了')
        }
      }).catch(err => {
        this.$alert(err.message, '网络连接出错')
      })
    },
    refuseAdd(username) {
      this.$axios.put(this.serverUrl+'/user/refuse', {
        friend: username,
        messages: JSON.stringify(this.messages),
      }, {
        headers: this.headers
      }).then(res => {
        if (res.data.status !== 0) {
          this.$alert(res.data.msg, '拒绝失败');
        } else {
          this.$delete(this.$store.state.messages[username], 'add');
          this.$message.warning('已拒绝了'+username+'的好友申请')
        }
      }).catch(err => {
        this.$alert(err.message, '网络连接出错')
      })
    },
    tryAgain(message) {
      this.$delete(this.$store.state.messages[message.user], message.action);
      this.isMsgShown = false;
      this.isAddShown = true;
      this.addFriendName = message.user;
    },
    giveUp(message) {
      this.$delete(this.$store.state.messages[message.user], message.action);
      // delete this.$store.state.messages[message.user][message.action];
      this.$axios.put(this.serverUrl+'/user/updateMsg', {
        messages: JSON.stringify(this.$store.state.messages)
      }, {
        headers: this.headers
      }).then(res => {
        if (res.data.status !== 0) {
          this.$alert(res.data.msg, '数据更新失败');
        }
      }).catch(err => {
        this.$alert(err.message, '网络连接出错')
      })
    }
  },
}
</script>

<style lang="scss" scoped>
  i {
    font-size: 30px !important;
    color: darkgray;
    cursor: pointer;
    &:hover {
     color: dodgerblue;
    }
  }

  #header {
    display: flex;
    align-items: center;
    padding: 3%;
    gap: 2%;
    span {
      &:first-child {
        margin-left: 5%;
        font-size: x-large;
        flex: 3;
      }
      &:nth-child(2) {
        flex: 1;
      }
      &:last-child {
        flex: 1;
      }
    }
  }

  #addInput {
    display: grid;
    grid-template-areas: 'input1 btn' 'input2 btn';
    grid-template-columns: 5fr 1fr;
    gap: 5%;
    place-items: center;
    .el-input {
      &:first-child {
        grid-area: input1;
      }
      &:nth-child(2) {
        grid-area: input2;
      }
    }
    i {
      grid-area: btn;
    }
  }

  .hide-button {
    opacity: 0;
    transition: opacity ease-in 0.2s;
    &:hover {
      opacity: 1;
    }
  }
</style>

